<template>
  <view class="search">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <nut-searchbar 
        v-model="searchValue" 
        placeholder="搜索商品" 
        @search="onSearch"
        @clear="clearSearch"
        :autofocus="true"
      />
    </view>

    <!-- 搜索历史 -->
    <view class="search-history" v-if="!searchValue && searchHistory.length > 0">
      <view class="history-header">
        <text class="title">搜索历史</text>
        <Del class="delete-icon" @click="clearHistory" />
      </view>
      <view class="history-tags">
        <nut-tag 
          v-for="(item, index) in searchHistory" 
          :key="index"
          plain
          @click="useHistoryItem(item)"
        >
          {{ item }}
        </nut-tag>
      </view>
    </view>

    <!-- 热门搜索 -->
    <view class="hot-search" v-if="!searchValue">
      <view class="hot-header">
        <text class="title">热门搜索</text>
      </view>
      <view class="hot-tags">
        <nut-tag 
          v-for="(item, index) in hotSearchList" 
          :key="index"
          plain
          type="primary"
          @click="useHistoryItem(item)"
        >
          {{ item }}
        </nut-tag>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-result" v-if="searchValue && !loading">
      <!-- 空结果提示 -->
      <nut-empty v-if="goodsList.length === 0" description="暂无相关商品" image="search" />

      <!-- 商品列表 -->
      <view v-else class="goods-list">
        <nut-grid :column-num="2" :border="false">
          <nut-grid-item
            v-for="(item, index) in goodsList"
            :key="index"
            @click="onGoodsClick(item)"
          >
            <view class="goods-card">
              <image :src="item.imgUrl" style="width: 100%; height: 150px; border-radius: 4px;" />
              <view class="goods-info">
                <view class="goods-name">{{ item.name }}</view>
                <view class="price-info">
                  <nut-price :price="item.price" size="normal" />
                  <nut-price v-if="item.vipPrice" :price="item.vipPrice" size="small" class="vip-price" />
                </view>
              </view>
            </view>
          </nut-grid-item>
        </nut-grid>
      </view>

      <!-- 加载更多 -->
      <view v-if="goodsList.length > 0" class="load-more">
        <view v-if="hasMore" class="loading" @click="loadMore">
          <Loading size="16px" /> 加载中...
        </view>
        <view v-else class="no-more">没有更多了</view>
      </view>
    </view>

    <!-- 加载中 -->
    <view class="loading-container" v-if="loading">
      <Loading type="spinner" size="24px" />
      <text>搜索中...</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import Taro from '@tarojs/taro'
import { Del, Loading } from '@nutui/icons-vue-taro'
import { useDebounce } from '@/hooks/useDebounce'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const keyword = router?.params?.keyword || ''

// 搜索相关
const searchValue = ref(keyword)
const loading = ref(false)
const currentPage = ref(1)
const hasMore = ref(true)

// 搜索历史
const searchHistory = ref<string[]>([])

// 热门搜索
const hotSearchList = ref([
  '手机',
  '笔记本',
  '耳机',
  '平板',
  '智能手表',
  '相机',
  '游戏机',
  '电视'
])

// 商品列表
const goodsList = ref([])

// 加载搜索历史
const loadSearchHistory = () => {
  const history = Taro.getStorageSync('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
}

// 保存搜索历史
const saveSearchHistory = (keyword: string) => {
  if (!keyword.trim()) return
  
  // 如果已存在，先移除
  const index = searchHistory.value.findIndex(item => item === keyword)
  if (index !== -1) {
    searchHistory.value.splice(index, 1)
  }
  
  // 添加到最前面
  searchHistory.value.unshift(keyword)
  
  // 最多保存10条
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }
  
  // 保存到本地
  Taro.setStorageSync('searchHistory', JSON.stringify(searchHistory.value))
}

// 清空搜索历史
const clearHistory = () => {
  Taro.showModal({
    title: '提示',
    content: '确定要清空搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        searchHistory.value = []
        Taro.removeStorageSync('searchHistory')
      }
    }
  })
}

// 使用历史记录项
const useHistoryItem = (item: string) => {
  searchValue.value = item
  onSearch(item)
}

// 清空搜索
const clearSearch = () => {
  goodsList.value = []
}

// 搜索商品
const searchGoods = async () => {
  if (!searchValue.value.trim()) {
    goodsList.value = []
    return
  }
  
  loading.value = true
  
  try {
    // 实际项目中应该调用API搜索商品
    // const res = await api.goods.searchGoods({
    //   keyword: searchValue.value,
    //   page: currentPage.value,
    //   pageSize: 10
    // })
    // goodsList.value = [...goodsList.value, ...res.list]
    // hasMore.value = res.hasMore
    
    // 模拟数据
    setTimeout(() => {
      const mockData = [
        {
          id: 1,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/223778/18/6959/103158/61cc7965E6f1e0dda/a4a0450759d5614e.jpg',
          name: 'iPhone 13 Pro',
          price: '5999',
          vipPrice: '5899'
        },
        {
          id: 2,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/106234/8/35183/153829/63f5c4b3Fca3f0094/1f0b2a3d37496aec.jpg',
          name: '华为 Mate 50 Pro',
          price: '6299',
          vipPrice: '6199'
        },
        {
          id: 3,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/177161/35/30849/53503/63f5c4b3F3d9c3d5d/8db7e7e2c3d1b6c0.jpg',
          name: '小米 13 Pro',
          price: '4999',
          vipPrice: '4899'
        },
        {
          id: 4,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/140200/32/33451/55488/63f5c4b3F1b7a9b9a/5e9b8b9b9b9b9b9b.jpg',
          name: 'OPPO Find X6 Pro',
          price: '5999',
          vipPrice: '5899'
        }
      ]
      
      if (currentPage.value === 1) {
        goodsList.value = mockData
      } else if (currentPage.value === 2) {
        goodsList.value = [...goodsList.value, ...mockData]
      } else {
        hasMore.value = false
      }
      
      loading.value = false
      
      // 保存搜索历史
      saveSearchHistory(searchValue.value)
    }, 500)
  } catch (error) {
    Taro.showToast({
      title: '搜索失败',
      icon: 'none'
    })
    loading.value = false
  }
}

// 防抖处理搜索
const debouncedSearch = useDebounce(searchGoods, 500)

// 监听搜索值变化
watch(searchValue, (newVal) => {
  if (newVal.trim()) {
    currentPage.value = 1
    hasMore.value = true
    debouncedSearch()
  } else {
    goodsList.value = []
  }
})

// 搜索处理
const onSearch = (val) => {
  if (!val.trim()) return
  
  searchValue.value = val
  currentPage.value = 1
  hasMore.value = true
  searchGoods()
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  
  currentPage.value++
  searchGoods()
}

// 点击商品
const onGoodsClick = (goods) => {
  Taro.navigateTo({
    url: `/pages/goods-details/index?id=${goods.id}`
  })
}

// 组件挂载时初始化
onMounted(() => {
  loadSearchHistory()
  
  // 如果有关键词，自动搜索
  if (searchValue.value) {
    searchGoods()
  }
})
</script>

<style lang="scss" scoped>
.search {
  padding: 10px;
  
  .search-bar {
    margin-bottom: 15px;
  }
  
  .search-history,
  .hot-search {
    margin-bottom: 20px;
    
    .history-header,
    .hot-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .title {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .history-tags,
    .hot-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
  
  .search-result {
    .goods-list {
      margin-bottom: 20px;
      
      .goods-card {
        display: flex;
        flex-direction: column;
        padding: 8px;
        
        .goods-info {
          padding: 8px 0;
          
          .goods-name {
            font-size: 14px;
            margin-bottom: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .price-info {
            display: flex;
            align-items: center;
            gap: 5px;
            
            .vip-price {
              color: #ff9500;
              text-decoration: line-through;
            }
          }
        }
      }
    }
    
    .load-more {
      text-align: center;
      color: #999;
      padding: 10px 0;
      font-size: 14px;
      
      .loading {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 5px;
      }
    }
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 200px;
    gap: 10px;
    color: #999;
  }
}
</style>